var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bid: '',
    weeks_ch: ['日', '一', '二', '三', '四', '五', '六'],
    days:[],
    imgs:[],//阅读剪影临时图片
    upurls: [],//阅读剪影图片

    hchjimgs: [],//好词好句好段临时图片
    hchjurls: [],//好词好句好段图片

    zjdhgimgs: [],//章节读后感临时图片
    zjdhgurls: [],//章节读后感图片

    goodsentence:'',//好词好句好段
    reaction: '',//章节读后感
    pagenum:'0',//今日所读页数
    timelen: '0', // 阅读时长
    minpage:0,//最低阅读量
    
    bookplan:'',//阅读计划

    imgcheck:false,//图片检测结果
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var usid = wx.getStorageSync('usid');
    if (usid == "") {
      wx.redirectTo({
        url: '../../pages/index/index'
      })
    } else {
      this.setData({
        bid: options.bid,
        usid: usid
      })
    }

    this.calculateDays();

    //查询本书打卡情况
    this.getBookreadLog();
  },

  //循环获取本周
  calculateDays() {
    const date = new Date();
    const todayindex = date.getDate();//本周当天的号数

    //本周第一天
    var nowdate = new Date();
    var weekFirstDay = new Date(nowdate - (nowdate.getDay() - 1) * 86400000);
    var firstday = weekFirstDay.getDate()-1;
    let days = [];


    for (let i = firstday; i <= parseInt(firstday)+6; i++) {
      var today = false;
      if (parseInt(i) == parseInt(todayindex)) {
        today = true;
      }
      var d = {
        text: i,
        result: false,
        progress: 'defalut',
        today: today,
      }
      days.push(d);
    }
    this.setData({
      days
    });
  },


  //好词好句好段
  getgoodsentence(e) {
    this.setData({
      goodsentence: e.detail.value
    })
  },

  //章节读后感
  getreaction(e) {
    this.setData({
      reaction: e.detail.value
    })
  },
 // 今日阅读页数
  pageinput(e) {
    this.setData({
      pagenum: e.detail.value
    })
  },

  //阅读时长
  timeleninput(e) {
    this.setData({
      timelen: e.detail.value
    })
  },

  //..............阅读剪影 start.................
  //上传图片
   uploadimage: function () {
    var that = this;
    wx.chooseImage({
      count: 4, //张数， 默认9
      sizeType: ['compressed'], //建议压缩图
      sourceType: ['album', 'camera'], // 来源是相册、相机
      success: function (res) {
        for (var i = 0; i < res.tempFilePaths.length; i++) {
            that.imgSecCheck_ydjy(res.tempFilePaths[i]);
        }
      }
    });
  },

  imgSecCheck_ydjy (imgitem) {
    var that=this;
    wx.showLoading({
      title: '图片检测中',
    })
    const uploadTask = app.wxupload({
      url: 'upload/imgSecCheck.html',
      filePath: imgitem,
      name: 'file',
      formData: {},
      success: function (res) {
        var datas = JSON.parse(res.data);
        wx.hideLoading();
        if(!datas.result){
          wx.showModal({
            title: '失败',
            content:datas.msg,
            showCancel: !1,
          });
          return;
        }else{
          var imgs = that.data.imgs;
          imgs.push(imgitem);
          that.setData({
            imgs: imgs
          })
        }
      }
    })
  },
  //删除图片
  delImage: function (e) {
    var that = this;
    var imgs = that.data.imgs;
    var cuindex = e.target.dataset.index;
    imgs.splice(cuindex, 1);
    that.setData({
      imgs: imgs
    })
  },
  //预览图片
  viewimage: function (e) {
    var cuindex = e.target.dataset.index;
    var that = this;
    var urls = that.data.imgs;
    wx.previewImage({
      current: urls[cuindex], // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  //..............阅读剪影 end.................







  //..............好词、好句、好段 start.................
  //上传图片
  uploadhchjhd: function () {
    var that = this;
    wx.chooseImage({
      count: 4, //张数， 默认9
      sizeType: ['compressed'], //建议压缩图
      sourceType: ['album', 'camera'], // 来源是相册、相机
      success: function (res) {
        var hchjimgs = that.data.hchjimgs;
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          that.imgSecCheck_hchjhd(res.tempFilePaths[i]);  
        }
        that.setData({
          hchjimgs: hchjimgs
        })
      }
    });
  },

  imgSecCheck_hchjhd (imgitem) {
    var that=this;
    wx.showLoading({
      title: '图片检测中',
    })
    const uploadTask = app.wxupload({
      url: 'upload/imgSecCheck.html',
      filePath: imgitem,
      name: 'file',
      formData: {},
      success: function (res) {
        console.log(res);
        var datas = JSON.parse(res.data);
        wx.hideLoading();
        if(!datas.result){
          wx.showModal({
            title: '失败',
            content:datas.msg,
            showCancel: !1,
          });
          return;
        }else{
          var hchjimgs = that.data.hchjimgs;
          hchjimgs.push(imgitem);
          that.setData({
            hchjimgs: hchjimgs
          })
        }
      }
    })
  },
  //删除图片
  delchjhdImage: function (e) {
    var that = this;
    var hchjimgs = that.data.hchjimgs;
    var cuindex = e.target.dataset.index;
    hchjimgs.splice(cuindex, 1);
    that.setData({
      hchjimgs: hchjimgs
    })
  },
  //预览图片
  viewchjhdimage: function (e) {
    var cuindex = e.target.dataset.index;
    var that = this;
    var urls = that.data.hchjimgs;
    wx.previewImage({
      current: urls[cuindex], // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  //..............好词、好句、好段 end.................






  //..............章节读后感 start.................
  //上传图片
   uploadzjdhgimage: function () {
    var that = this;
    wx.chooseImage({
      count: 4, //张数， 默认9
      sizeType: ['compressed'], //建议压缩图
      sourceType: ['album', 'camera'], // 来源是相册、相机
      success: function (res) {
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          that.imgSecCheck_zjdhg(res.tempFilePaths[i]);
        }
      }
    });
  },
  
  imgSecCheck_zjdhg (imgitem) {
    var that=this;
    wx.showLoading({
      title: '图片检测中',
    })
    const uploadTask = app.wxupload({
      url: 'upload/imgSecCheck.html',
      filePath: imgitem,
      name: 'file',
      formData: {},
      success: function (res) {
        var datas = JSON.parse(res.data);
        wx.hideLoading();
        if(!datas.result){
          wx.showModal({
            title: '失败',
            content:datas.msg,
            showCancel: !1,
          });
          return;
        }else{
          var zjdhgimgs = that.data.zjdhgimgs;
          zjdhgimgs.push(imgitem);
          that.setData({
            zjdhgimgs: zjdhgimgs
          })
        }
      }
    })
  },
  //删除图片
  delzjdhgImage: function (e) {
    var that = this;
    var zjdhgimgs = that.data.zjdhgimgs;
    var cuindex = e.target.dataset.index;
    zjdhgimgs.splice(cuindex, 1);
    that.setData({
      zjdhgimgs: zjdhgimgs
    })
  },
  //预览图片
  viewzjdhgimage: function (e) {
    var cuindex = e.target.dataset.index;
    var that = this;
    var urls = that.data.zjdhgimgs;
    wx.previewImage({
      current: urls[cuindex], // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    })
  },
  //..............章节读后感 end.................


  getBookreadLog(e) {
    var that = this;
    var bid = that.data.bid;
    var usid = that.data.usid;
    app.wxget({
      url: 'wdsj/getBookreadLog.html',
      data: {
        bid: bid,
        usid: usid
      },
      success: function (res) {
        var logs = res.data.logs;
        if (logs) {
          that.setData({
            logs: logs
          })
        }
        console.log(res.data);
        that.setData({
          bookplan: {
            PLANID: res.data.PLANID,
            USID: res.data.USID,
            MINPAGE: res.data.MINPAGE,
            USERNAME: res.data.USERNAME,
            ADDTIME: res.data.ADDTIME,
            JD: res.data.JD,
            BOOKNAME: res.data.BOOKNAME,
            TOTALPAGE: res.data.TOTALPAGE,
            MINNUM: res.data.MINNUM,
            NJ: res.data.NJ,
            BJ: res.data.BJ,
            AUTHOR: res.data.AUTHOR,
            REASON: res.data.REASON,
            RECOMMENDOR: res.data.RECOMMENDOR,
            SH: res.data.SH,
            BOOKJJ: res.data.BOOKJJ,
            AUTHORJJ: res.data.AUTHORJJ,
            BOOKXX: res.data.BOOKXX,
            TJLY: res.data.TJLY,
            PAGENUM: res.data.PAGENUM,
          }
        });
        wx.setNavigationBarTitle({
          title: "《" + res.data.BOOKNAME + "》"
        })
        that.calculatePlanDays();
      }
    })
  },


  calculatePlanDays() {
    var days = this.data.days;
    var bookplan=this.data.bookplan;
    //当前年 当前月
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    //本书打卡记录
    var logs = this.data.logs;
    //今天的号数
    var todayIndex = this.data.todayIndex;
    var today = parseInt(todayIndex) + 1;
    if (logs){
      for (var i = 0; i < days.length; i++) {
        var di = days[i];
        for (var j = 0; j < logs.length; j++) {
          var logj = logs[j];
          //同一天
          if ((parseInt(cur_year) == parseInt(logj.YEAR)) && (parseInt(cur_month) == parseInt(logj.MONTH))) {
            if ((parseInt(di.text) == parseInt(logj.DAY))) {
              if (j == 0) {
                days[i].text = "开始";
                days[i].progress = "start";
              } else if (j == (logs.length - 1)) {
                if (bookplan.JD == '100') {
                  days[i].text = "结束";
                  days[i].progress = "end";
                } else {
                  days[i].progress = "ing";
                }
              } else {
                days[i].progress = "ing";
              }
              if (logj.PAGENUM == bookplan.MINNUM) {
                days[i].result = true;
              } else {
                days[i].result = false;
              }
              if (parseInt(di.text) == parseInt(today)) {
                days[i].today = true;
              }
            }
          }
          //同一天
        }
      }
    }
    
    this.setData({
      days: days
    })
  },


  surereadlog() {
    var that = this;
    var goodsentence = that.data.goodsentence;
    var pagenum = that.data.pagenum;
    if (pagenum == '' || pagenum==0) {
      wx.showModal({
        title: '友情提示',
        content: '请填写今天阅读的页数!',
        showCancel: !1,
      })
      return;
    }

    var timelen = that.data.timelen;
    if (timelen == '' || timelen==0) {
      wx.showModal({
        title: '友情提示',
        content: '请填写今天阅读的时长（单位：分钟）!',
        showCancel: !1,
      })
      return;
    }

    //阅读剪影图片
    var imgs = this.data.imgs;
    //好词好句好段临时图片
    var hchjimgs = this.data.hchjimgs;
    //章节读后感临时图片
    var zjdhgimgs = this.data.zjdhgimgs;

    //好词好句好段为必填
    if (goodsentence == "" && hchjimgs.length<=0){
      wx.showModal({
        title: '友情提示',
        content: '请填写好词好句好段或上传图片!',
        showCancel: !1,
      })
      return;
    }
  
    //阅读剪影
    if (imgs.length <= 0) {
      wx.showModal({
        title: '友情提示',
        content: '请上传阅读剪影!',
        showCancel: !1,
      })
      return;
    }

    wx.showLoading({
      title: '保存中',
    })
    that.setData({
      disabled: true,
      loading: true
    })

    if (imgs.length > 0) {
      //上传阅读剪影图片
      that.uploadBookurl();
    }else if (hchjimgs.length > 0) {
      //上传好词好句好段图片
      that.uploadBookHchjhdurl();
    }else if (zjdhgimgs.length > 0) {
      //上传章节读后感图片
      that.uploadBookZjdhgurl();
    }else {
      that.savereadlog();
    }
  },



  //提交阅读剪影图片
  uploadBookurl: function () {
    var that = this;
    //好词好句好段临时图片
    var hchjimgs = this.data.hchjimgs;
    //章节读后感临时图片
    var zjdhgimgs = this.data.zjdhgimgs;
    //阅读剪影图片
    var imgs = this.data.imgs;
    var upurls = this.data.upurls;
    const uploadTask = app.wxupload({
      url: 'upload/uploadwx.html?savefile=ydjy',
      filePath: imgs[0],
      name: 'file',
      formData: {},
      success: function (res) {
        var img = JSON.parse(res.data);
        var url = img.urls;
        upurls.push(url);
        that.setData({
          upurls: upurls
        });
        that.data.imgs.splice(0, 1);
        if (that.data.imgs.length > 0) {
          that.uploadBookurl();
        }else if (hchjimgs.length > 0){
          //上传好词好句好段图片
          that.uploadBookHchjhdurl();
        }else if (zjdhgimgs.length > 0) {
          //上传章节读后感图片
          that.uploadBookZjdhgurl();
        }else{
          that.savereadlog();
        }
      }
    })
  },

  

  //提交好词好句好段图片
  uploadBookHchjhdurl: function () {
    //章节读后感临时图片
    var zjdhgimgs = this.data.zjdhgimgs;
    var that = this;
    var hchjimgs = this.data.hchjimgs;
    var hchjurls = this.data.hchjurls;
    const uploadTask = app.wxupload({
      url: 'upload/uploadwx.html?savefile=hchjhd',
      filePath: hchjimgs[0],
      name: 'file',
      formData: {},
      success: function (res) {
        var img = JSON.parse(res.data);
        var url = img.urls;
        hchjurls.push(url);
        that.setData({
          hchjurls: hchjurls
        });
        that.data.hchjimgs.splice(0, 1);
        if (that.data.hchjimgs.length > 0) {
          that.uploadBookHchjhdurl();
        }else if (zjdhgimgs.length > 0) {
          //上传章节读后感图片
          that.uploadBookZjdhgurl();
        }else{
          that.savereadlog();
        }
      }
    })
  },


   //提交章节读后感图片
  uploadBookZjdhgurl: function() {
    var that = this;
    var zjdhgimgs = this.data.zjdhgimgs;
    var zjdhgurls = this.data.zjdhgurls;
    const uploadTask = app.wxupload({
      url: 'upload/uploadwx.html?savefile=zjdhg',
      filePath: zjdhgimgs[0],
      name: 'file',
      formData: {},
      success: function (res) {
        var img = JSON.parse(res.data);
        var url = img.urls;
        zjdhgurls.push(url);
        that.setData({
          zjdhgurls: zjdhgurls
        });
        that.data.zjdhgimgs.splice(0, 1);
        if (that.data.zjdhgimgs.length > 0) {
          that.uploadBookZjdhgurl();
        } else {
          that.savereadlog();
        }
      }
    })
  },


  savereadlog() {
    var that=this;
    var planid = this.data.bookplan.PLANID;
    var bid=this.data.bid;
    var pagenum = this.data.pagenum;
    //阅读时长
    var timelen = that.data.timelen;
    var goodsentence = this.data.goodsentence;
    var reaction = this.data.reaction;
    var usid = wx.getStorageSync('usid');
    var username = wx.getStorageSync('name');
    var totalpage = this.data.bookplan.TOTALPAGE;//书的总页数
    var minnum = this.data.bookplan.MINNUM;//每天最低读书量
    var upurls = this.data.upurls;//阅读剪影
    var hchjurls = this.data.hchjurls;//好词好句好段
    var zjdhgurls = this.data.zjdhgurls;//章节读后感图片
    var totalyd = this.data.bookplan.PAGENUM;
    app.wxget({
      url: 'wdsj/savereadlog.html',
      data: {
        planid: planid,
        bid: bid,
        pagenum: pagenum,
        timelen: timelen,
        goodsentence: goodsentence,
        reaction: reaction,
        usid: usid,
        username: username,
        totalpage: totalpage,
        minnum: minnum,
        upurls: upurls,
        hchjurls: hchjurls,
        zjdhgurls: zjdhgurls,
        totalyd: totalyd
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.result){
          wx.showModal({
            title: '成功',
            content: '打卡成功!',
            showCancel: !1,
          });
          wx.redirectTo({
            url: '../../pages/bookydjl/bookydjl?bid=' + bid
          })
        }else{
          wx.showModal({
            title: '失败',
            content: res.data.msg,
            showCancel: !1,
          });
        }
      }
    })
  },

})